<?php

class FormControl extends TemplateLoader
{
	public $Bean; // the bean
	public $Type = 'text'; // type
	public $IsBound = true; // is the field databound
	public $CanPost = true; // can the field be loaded through post
	public $Message = ''; // error message
	public function FormControl($Bean = NULL, $FieldName = NULL)
	{
		parent::__construct( );
				
		$this->Module = 'System/Controls/Forms';
		$this->Template = 'templates/FormControlText.tpl';
		
		if(!is_null ( $Bean ))
			$this->Bean = $Bean;
		if(!is_null ( $FieldName ))
			$this->FieldName = $FieldName;
	}
	public function GetValue( )
	{
		if($this->IsBound)
		{
			$FieldName = $this->FieldName;
			return $this->Bean->$FieldName;
		}
		if(isset($this->Value))
			return $this->Value;
		return '';
	}
	public function SetUnvalidatedValue( $Value )
	{
		if($this->IsBound)
		{
			$FieldName = $this->FieldName;
					$this->Bean->$FieldName = $Value;
		}
		else
			$this->Value = $Value;
	}
	
	public function SetValue( $Value )
	{
		if(isset($this->Validators))
			foreach ($this->Validators as $validator)
			{
				$error = $validator->Validate( $Value );
				if($error != null)
				{
					$this->Message = $error;
					return false;
				}			
			}
		if( isset( $this->Validator ) )
		{
			$error = $this->Validator->Validate( $Value );
			if($error == null)
			{
				$this->SetUnvalidatedValue( $Value );
			}
			else
			{
				$this->Message = $error;
				return false;
			}			
		}
		else
			$this->SetUnvalidatedValue( $Value );
		return true;
	}
	public function LoadPostData( )
	{
		if( $this->CanPost && isset( $_POST[$this->FieldName]))
			return $this->SetValue($_POST[$this->FieldName]);
		return true;
	}
}
